//
//  ServiceVC.m
//  UHealth
//
//  Created by gjtxz on 14/12/29.
//  Copyright (c) 2014年 gjtx. All rights reserved.
//

#import "ServiceVC.h"
#import "OtherServiceCell.h"
#import "MJRefresh.h"
#import "AFNetworking.h"
#import "iToast.h"
#import "ServiceCell.h"
#import "howUseVC.h"
#import "ServiceInfoVC.h"

@interface ServiceVC ()<UITableViewDelegate,UITableViewDataSource>

@property (nonatomic, strong)  UITableView        *contentTableView;
@property (nonatomic, strong)  NSArray            *dataArray;

@property (nonatomic, strong)  ServiceCell        *cell;

@property (nonatomic, strong)  UIImageView        *img;

@end

@implementation ServiceVC

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
        [self initView];
    }
    return self;
}

- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    [MobClick beginLogPageView:kLocal(@"Service")];
}

- (void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
    [MobClick endLogPageView:kLocal(@"Service")];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

-(void) initView
{
    self.view.backgroundColor = kBacColor;
//    self.title = kLocal(@"Service");
    self.title = @"服务";
    self.navigationItem.title = kLocal(@"Custom Service");
    self.tabBarItem.image = [UIImage imageNamed:@"service_grey"];
    self.tabBarItem.selectedImage = [UIImage imageNamed:@"service_blue"];
    self.navigationItem.title = kLocal(@"Custom Service");
    
    
    UIButton *useBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    useBtn.frame = CGRectMake(0, kNavHeight, WIDTH/2, 40);
    [useBtn.layer setMasksToBounds:YES];
    [useBtn.layer setCornerRadius:1.0];//设置矩形是个圆角半径
    useBtn.backgroundColor = kBacColor;
    [useBtn setTitle:kLocal(@"useBtn") forState:UIControlStateNormal];
    [useBtn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    [useBtn setImage:[UIImage imageNamed:@"pic_user_bg"] forState:UIControlStateNormal];
    if (VIEW_3_5_INCH) {
        useBtn.titleLabel.font = [UIFont systemFontOfSize:14];
    }else if (VIEW_4_INCH){
        useBtn.titleLabel.font = [UIFont systemFontOfSize:14];
    }else if (VIEW_4_7_INCH){
        useBtn.titleLabel.font = [UIFont systemFontOfSize:15];
    }else if (VIEW_5_5_INCH){
        useBtn.titleLabel.font = [UIFont systemFontOfSize:16];
    }
    [useBtn addTarget:self action:@selector(btnClick:) forControlEvents:UIControlEventTouchUpInside];
    useBtn.tag = 1;
    [self.view addSubview:useBtn];
    
    
    UIButton *dayBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    dayBtn.frame = CGRectMake(WIDTH/2, kNavHeight, WIDTH/2, 40);
    [dayBtn.layer setMasksToBounds:YES];
    [dayBtn.layer setCornerRadius:1.0];//设置矩形是个圆角半径
    dayBtn.backgroundColor =kBacColor;
    [dayBtn setTitle:kLocal(@"dayBtn") forState:UIControlStateNormal];
    [dayBtn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    [dayBtn setImage:[UIImage imageNamed:@"pic_course_bg"] forState:UIControlStateNormal];
    if (VIEW_3_5_INCH) {
        dayBtn.titleLabel.font = [UIFont systemFontOfSize:14];
    }else if (VIEW_4_INCH){
        dayBtn.titleLabel.font = [UIFont systemFontOfSize:14];
    }else if (VIEW_4_7_INCH){
        dayBtn.titleLabel.font = [UIFont systemFontOfSize:15];
    }else if (VIEW_5_5_INCH){
        dayBtn.titleLabel.font = [UIFont systemFontOfSize:16];
    }
    [dayBtn addTarget:self action:@selector(btnClick:) forControlEvents:UIControlEventTouchUpInside];
    dayBtn.tag = 2;
    [self.view addSubview:dayBtn];

    
    _img = [[UIImageView alloc]initWithImage:[UIImage imageNamed:@"none"]];
    _img.frame = CGRectMake(130, 200 ,WIDTH-260, WIDTH-260);
    
    _contentTableView = [[UITableView alloc]initWithFrame:CGRectMake(0, kNavHeight+40, WIDTH, HEIGHT- kNavHeight - 40-kTabBarHeight) style:UITableViewStyleGrouped];
    _contentTableView.delegate = self;
    _contentTableView.dataSource = self;
    [_contentTableView setSeparatorInset:UIEdgeInsetsZero];
    __unsafe_unretained typeof(self) vc = self;
    
    [_contentTableView addHeaderWithCallback:^{
        if(!kNetIsOK){
            [vc.contentTableView headerEndRefreshing];
            [[iToast makeText:kLocal(@"netNoOk")] show];
            return ;
        }
        AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
        manager.requestSerializer.timeoutInterval = 5;
        manager.responseSerializer.acceptableContentTypes = [manager.responseSerializer.acceptableContentTypes setByAddingObject: @"text/html"];
        NSString *postStr = [NSString stringWithFormat:@"%@/action/json/shop.jsp?",kBaseUrl];
        NSDictionary *parameters = @{@"action": @"getall",
                                     @"userid":[NSString stringWithFormat:@"%ld",(long)kNetID],
                                     @"fromtype":@"2",
                                     @"pages":@"1",};
        [manager POST:postStr parameters:parameters success:^(AFHTTPRequestOperation *operation, id responseObject) {
            //            kDebug(@"Success: %@", operation.responseString);
            BOOL type = [[responseObject objectForKey:@"type"] boolValue];
            if(type){//成功
                
                vc.dataArray = [responseObject objectForKey:@"shopArr"];
                if (vc.dataArray.count > 0) {
                    vc.img.hidden = YES;
                }else{
                    vc.img.hidden = NO;
                }
                [vc.contentTableView reloadData];
            }else{
                
            }
            //            [[iToast makeText:[responseObject objectForKey:@"msg"]] show];
            [vc.contentTableView headerEndRefreshing];
        } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
            kDebug(@"Error: %@", error);
            [vc.contentTableView headerEndRefreshing];
            [[iToast makeText:kLocal(@"netError")] show];
        }];
        
    }];
    [self.view addSubview:_contentTableView];
    
    [_contentTableView headerBeginRefreshing];
    
    [_contentTableView registerNib:[UINib nibWithNibName:NSStringFromClass([ServiceCell class]) bundle:[NSBundle mainBundle]] forCellReuseIdentifier:NSStringFromClass([ServiceCell class])];
    
    [self.view addSubview:_img];


    
    
//    self.dataArray = @[@{@"imglStr":@"cloud",@"serviceLabelStr":@"名医专家慢病服务",@"detailLabelStr":@"丰富的格格热个人个人D大调是飒飒阿斯顿发放的凤飞飞供热个人各个各个而二哥二哥哥ffffffsgdsgsgsgsgwgwgaggregergesgregesghseghergergergergergergergegegregegegeeawea34",@"costLabelStr":@"1200/年",@"scanLabelStr":@"浏览人数：1136"},
//                       @{@"imglStr":@"doctor_service",@"serviceLabelStr":@"名医专家慢病服务",@"detailLabelStr":@"丰富的格格热反复发多少凡人人人人人人人个人个人供热个人各个各个而二哥二哥哥",@"costLabelStr":@"1200/年",@"scanLabelStr":@"浏览人数：1136"}];
//    _contentTableView = [[UITableView alloc]initWithFrame:self.view.bounds style:UITableViewStyleGrouped];
//    _contentTableView.delegate = self;
//    _contentTableView.dataSource = self;
//    __unsafe_unretained typeof(self) vc = self;
//    
//    [_contentTableView addHeaderWithCallback:^{
//         
//        // 模拟延迟加载数据，
//        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
//            // 结束刷新
//            
//            [vc.contentTableView headerEndRefreshing];
//        });
//    }];
//    [self.view addSubview:_contentTableView];
//    
//    [_contentTableView registerNib:[UINib nibWithNibName:NSStringFromClass([OtherServiceCell class]) bundle:[NSBundle mainBundle]] forCellReuseIdentifier:NSStringFromClass([OtherServiceCell class])];
}


-(void)btnClick:(UIButton *)btn
{
    [self presentViewController:[[howUseVC alloc]initWithChoice:btn.tag andTitle:btn.titleLabel.text] animated:YES completion:nil];
    //    [self.navigationController pushViewController:[[howUseVC alloc]init] animated:YES];
}

- (ServiceCell *)cell
{
    if (!_cell) {
        _cell = [self.contentTableView dequeueReusableCellWithIdentifier:NSStringFromClass([ServiceCell class])];
    }
    return _cell;
}



#pragma mark - UITableViewDelegate && UITableViewDataSource
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return _dataArray.count;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return 1;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 120;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    ServiceCell *cell = [tableView dequeueReusableCellWithIdentifier:NSStringFromClass([ServiceCell class]) forIndexPath:indexPath];
    [cell setData:_dataArray[indexPath.section]];
    [cell updateConstraintsIfNeeded];
    [cell layoutIfNeeded];
    
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:NO];
    ServiceInfoVC *ser = [[ServiceInfoVC alloc]initWithDic:_dataArray[indexPath.section]];
    [self presentViewController:ser animated:YES completion:nil];
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 1;
}
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    return 9;
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
